package com.hsh.erp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hsh.erp.domain.common.Result;
import com.hsh.erp.domain.dto.RepositoryDTO;
import com.hsh.erp.domain.entity.Repository;
import com.hsh.erp.domain.vo.RepositoryVO;
import com.hsh.erp.init.DataInitializer;
import com.hsh.erp.mapper.RepositoryMapper;
import com.hsh.erp.service.RepositoryService;
import com.hsh.erp.utils.MyBeanUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


/**
 * @author USER
 * @description 针对表【repository】的数据库操作Service实现
 * @createDate 2024-05-30 16:21:43
 */
@Service
public class RepositoryServiceImpl extends ServiceImpl<RepositoryMapper, Repository>
        implements RepositoryService {
    @Resource
    private DataInitializer dataInitializer;

    /**
     * 获取所有未删除的仓库
     *
     * @return
     */
    @Override
    public Result<List<RepositoryDTO>> getAll() {
        List<RepositoryDTO> repositoryDTOList = DataInitializer.getRepositoryDTOList();
        if (repositoryDTOList.isEmpty()) {
            return getList(new RepositoryVO().setIsDelete(0));
        }
        return Result.success(repositoryDTOList);
    }

    /**
     * 列表查询
     *
     * @param repositoryVO
     * @return
     */
    @Override
    public Result<List<RepositoryDTO>> getList(RepositoryVO repositoryVO) {
        repositoryVO.selectInit();
        QueryWrapper wrapper = new QueryWrapper<>()
                .like(Strings.isNotBlank(repositoryVO.getName()), "name", repositoryVO.getName())
                .eq(repositoryVO.getIsDelete() != null, "is_delete", repositoryVO.getIsDelete());
        List<RepositoryDTO> repositoryDTOList
                = MyBeanUtils.copyList(list(wrapper), RepositoryDTO.class);
        return Result.success(repositoryDTOList);
    }

    /**
     * 修改一条记录
     *
     * @param repositoryVO
     * @return
     */
    @Override
    public Result updateOne(RepositoryVO repositoryVO) {
        boolean update = updateById(MyBeanUtils.copy(repositoryVO, Repository.class));
        dataInitializer.initRepository();
        return Result.create(update);
    }

    /**
     * 删除或者恢复 一条记录
     *
     * @param repositoryVO
     * @return
     */
    @Override
    public Result deleteOne(RepositoryVO repositoryVO) {
        UpdateWrapper wrapper = new UpdateWrapper<>()
                .set("is_delete", repositoryVO.getIsDelete())
                .eq("id", repositoryVO.getId())
                // 删除时（0->1），只能删除非默认的仓库
                .eq(repositoryVO.getIsDelete() != 0, "is_default", 0);
        boolean update = update(wrapper);
        dataInitializer.initRepository();
        return Result.create(update);
    }

    /**
     * 新增一条记录
     *
     * @param repositoryVO
     * @return
     */
    @Override
    public Result addOne(RepositoryVO repositoryVO) {
        boolean save = save(MyBeanUtils.copy(repositoryVO, Repository.class));
        dataInitializer.initRepository();
        return Result.create(save);
    }


    /**
     * 根据id获取名称
     *
     * @param id
     * @return
     */
    @Override
    public String getNameById(Integer id) {
        // 获取缓存
        Map<Integer, String> repositoryMap = DataInitializer.getRepositoryMap();
        // 通过数据库获取并写到缓存，再次获取缓存
        if (repositoryMap == null || repositoryMap.isEmpty()) {
            repositoryMap = dataInitializer.initRepository();
        }
        return repositoryMap.get(id);
    }

    /**
     * 设置为默认仓库，其他仓库设置为非默认仓库
     *
     * @param repositoryVO
     * @return
     */
    @Override
    @Transactional
    public Result setDefault(RepositoryVO repositoryVO) {
        Integer defaultId = repositoryVO.getId();
        // 将原本 默认仓库 设置为 非默认
        boolean updateAllNotDefault = update(new UpdateWrapper<Repository>()
                .set("is_default", 0)
                .eq("is_default", 1));

        // 设置 defaultId 的仓库 为默认仓库
        boolean setDefault = updateOne(repositoryVO.setIsDefault(1)).isSuccess();

        // 更新缓存
        dataInitializer.initRepository();

        return Result.create(updateAllNotDefault && setDefault);
    }
    //============================================私有方法开始============================================
    //============================================私有方法结束============================================
}




